from concurrent.futures.thread import ThreadPoolExecutor
import openpyxl
import requests

proxies = {
    'http': 'socks5://127.0.0.1:10000',
    'https': 'socks5://127.0.0.1:10000'
}
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
              'application/signed-exchange;v=b3;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/87.0.4280.141 Safari/537.36',
}
n_threads = 5
def download_video(id):
    # 打开excel表中sheet部分
    excel = openpyxl.load_workbook('C:/Users/Administrator/Desktop/video.xlsx')
    sheet = excel['Sheet1']
    # 行数
    row = id
    image_url = sheet.cell(row, 1).value
    print('开始下载第' + str(id) + '个封面图片')
    if image_url:
        try:
            # 请求视频地址，超时时间为300s
            res = requests.get(image_url, headers=headers, proxies=proxies, timeout=300)
            f = open('image/' + str(row) + '.png', 'wb')
            f.write(res.content)
            f.close()
            res.close()
            # 第rows行第10列赋值为下载成功
            # sheet.cell(row, 2).value = str('下载成功')
            # excel.save('C:/Users/Administrator/Desktop/image.xlsx')
            print('第' + str(row) + '个图片下载完成')
            excel.close()
        except Exception:
            # sheet.cell(row, 2).value = str('下载超时')
            # excel.save('C:/Users/Administrator/Desktop/image.xlsx')
            print('第' + str(row) + '个图片下载超时')
            excel.close()
    else:
        # sheet.cell(row, 12).value = str('下载失败')
        # excel.save('C:/Users/Administrator/Desktop/image.xlsx')
        print('第' + str(row) + '个图片下载失败')
        excel.close()


if __name__ == '__main__':
    id = range(2, 167)
    with ThreadPoolExecutor(max_workers=n_threads) as pool:
            pool.map(download_video, id)

